import { Form, Input, Modal, Button, Select } from "antd";
import React, { Component } from "react";
import UploadImage from "@/components/UploadImage";
import { UserJobStatus } from "@/utils/enum";
import styles from "../index.less";

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

const formItemLayout = {
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 15 }
  },
  labelCol: {
    xs: { span: 22 },
    sm: { span: 6 }
  }
};

class CreateUpdateForm extends Component {
  static defaultProps = {
    formVals: {}
  };

  constructor(props) {
    super(props);
    this.state = {
      fileList: []
    };
  }

  componentDidMount() {}

  // 避免组件重复或者无意义渲染
  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps) == JSON.stringify(this.props)) return;
    this.freezeUrls(nextProps);
  }

  freezeUrls = nextProps => {
    const { reportAnnexList } = nextProps.formVals;
    const urlsArray = [];
    if (reportAnnexList) {
      reportAnnexList.map(item => {
        const urls = {
          url: item.annexUrl,
          uid: item.id,
          response: { url: item.annexUrl }
        };
        urlsArray.push(urls);
      });
    }
    this.setState({
      fileList: urlsArray
    });
  };

  handleVoucherChange = info => {
    const list = Array.isArray(info) ? info : info.fileList;
    this.setState({ voucherList: list });
  };

  handleOk = () => {
    const { form, onSubmit, formVals } = this.props;
    form.validateFields((err, values) => {
      if (err) return;
      const reportAnnexList = [];
      if (values.reportAnnexList[0].response) {
        Array.isArray(values.reportAnnexList)
          ? values.reportAnnexList.map(item =>
              reportAnnexList.push({
                annexUrl: item.response.url,
                annexType: "PICTURE"
              })
            )
          : "";
      } else {
        Array.isArray(values.reportAnnexList)
          ? values.reportAnnexList.map(item =>
              reportAnnexList.push({ annexUrl: item.url, annexType: "PICTURE" })
            )
          : "";
      }
      const params = {
        ...values,
        reportAnnexList,
        id: formVals.id
      };
      onSubmit(params);
      form.resetFields();
    });
  };

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  render() {
    const { modalVisible, form, onCancel, formVals } = this.props;
    const { fileList } = this.state;
    return (
      <Modal
        destroyOnClose
        title={formVals.id ? "编辑进度汇报" : "添加进度汇报"}
        visible={modalVisible}
        onCancel={() => onCancel()}
        className={styles.formWarp}
        footer={[
          <Button key="submit" type="primary" onClick={this.handleOk}>
            {formVals.id ? "确认保存" : "确认添加"}
          </Button>
        ]}
      >
        <FormItem label="承揽方" {...formItemLayout}>
          <Input value={formVals.name} allowClear disabled />
        </FormItem>

        {!formVals.id && (
          <FormItem label="服务进度" {...formItemLayout}>
            {form.getFieldDecorator("userJobStatus", {
              rules: [{ required: true, message: "请选择服务进度" }]
            })(
              <Select
                allowClear
                style={{ width: "100%" }}
                placeholder="请选择服务进度"
              >
                {UserJobStatus.map(item => (
                  <Option key={item.value} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
        )}

        <FormItem label="进度描述" {...formItemLayout}>
          {form.getFieldDecorator("description", {
            rules: [{ required: true, message: "请输入进度描述" }],
            initialValue: formVals.description
          })(<TextArea rows={4} maxLength={300} />)}
        </FormItem>

        <Form.Item label="上传图片" {...formItemLayout}>
          {form.getFieldDecorator("reportAnnexList", {
            valuePropName: "fileList",
            getValueFromEvent: this.normFile,
            initialValue: fileList,
            rules: [
              { type: "array", max: 6, message: "最多上传6张" },
              { required: true, message: "请上传图片" }
            ]
          })(
            <UploadImage
              showUploadBtn={fileList.length < 6}
              onChange={this.handleVoucherChange}
            />
          )}
        </Form.Item>
      </Modal>
    );
  }
}

export default Form.create()(CreateUpdateForm);
